package com.dtz.rabbitmq.workqueuen.lunxun;

import java.io.IOException;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;

public class Consumer2 {

	public static void main(String[] args) {
		// 1、创建连接工厂
		ConnectionFactory factory = new ConnectionFactory();
		factory.setVirtualHost("/");
		factory.setHost("1.15.137.13");
		factory.setPort(5672);
		factory.setUsername("admin");
		factory.setPassword("admin");
		
		Connection connection = null;
		Channel channel = null;
		
		try {
			
			connection = factory.newConnection();
			
			channel = connection.createChannel();
			
			// 接收消息
			channel.basicConsume("WR-queuen1", true, new DeliverCallback() {
				
				@Override
				public void handle(String consumerTag, Delivery message) throws IOException {
					System.out.println("work02获得消息：" + new String(message.getBody(), "utf-8"));
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}, new CancelCallback() {
				
				@Override
				public void handle(String consumerTag) throws IOException {
					System.out.println("获得消息失败");
				}
			});
			
			 System.out.println("Work02-开始接受消息");
	         System.in.read();
			
		} catch (Exception e) {
			// TODO: handle exception
		} finally
		{
			// 9: 释放连接关闭通道
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
		}
	}
	
}
